package response

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

const (
	ERROR   = 7
	SUCCESS = 0
)

func Result(code int, data interface{}, msg string, c *gin.Context) {
	//j, _ := json.Marshal(data)
	//reg := regexp.MustCompile(`id\":(\d{16,20}),"`)
	//l := len(reg.FindAllString(string(j), -1)) //正则匹配16-20位的数字，如果找到了就开始正则替换并解析
	//if l != 0 {
	//	fmt.Printf("\n正则替换前的数据%+v", data)
	//	var mapResult map[string]interface{}
	//	str := reg.ReplaceAllString(string(j), `id": "${1}","`)
	//	json.Unmarshal([]byte(str), &mapResult)
	//	data = &mapResult
	//}

	c.JSON(http.StatusOK, Response{
		code,
		data,
		msg,
	})
}

func Ok(c *gin.Context) {
	Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
}

func OkWithMessage(message string, c *gin.Context) {
	Result(SUCCESS, map[string]interface{}{}, message, c)
}

func OkWithData(data interface{}, c *gin.Context) {
	Result(SUCCESS, data, "查询成功", c)
}

func OkWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(SUCCESS, data, message, c)
}

func Fail(c *gin.Context) {
	Result(ERROR, map[string]interface{}{}, "操作失败", c)
}

func FailWithMessage(message string, c *gin.Context) {
	Result(ERROR, map[string]interface{}{}, message, c)
}

func FailWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(ERROR, data, message, c)
}

func FailValidationCode(data interface{}, code string, message string, c *gin.Context) {
	atoi, _ := strconv.Atoi(code)
	Result(atoi, data, message, c)
}
